import yaml
import argparse
from sys import argv
from os import getcwd
from os.path import expanduser

def getOptions():
    '''
    Analizu datumoj
    '''
    args = argv[1:]
    parser = argparse.ArgumentParser(description="Parses command.",argument_default=argparse.SUPPRESS)
    parser.add_argument("echo",nargs="?")
    parser.add_argument("-s", "--shared",nargs="?",
                        help="Directory containing shared resources, such as soundfonts, samples, etc.")
    parser.add_argument("-c", "--config",nargs="?",
                        help="Optional path to a non-default config file.")
    parser.add_argument("-t", "--type",nargs="?",
                        help="Type of directory tree to create. Defaults to 'default'.")
    parser.add_argument("-d", "--destination",nargs="?",
                        help="Destination of where you want to create your project. Defaults to pwd.")
    parser.add_argument("-g", "--gui",dest='gui',action='store_true',help="Run the GUI.")
    parser.add_argument("-q", "--quiet",dest='quiet',action='store_true',help="Do not notify me when finished.")

    options = parser.parse_args(args)
    opts = vars(options)

    if not opts.get('destination'):
        opts['destination'] = getcwd()

    if not opts.get('config'):
        try:
            opts['config'] = os.path.join(os.expanduser('~') + '.config' + 'planter' + 'tree.list')
        except:
            opts['config'] = '/etc/planter/tree.list'

    if opts.get('destination'):
        opts['destination'] = expanduser(opts['destination'])

    with open(opts['config']) as stream:
        f = stream.read()
    cdc = yaml.load(f)
    for key,val in cdc.items():
        if key == 'var':
            for k in val:
                for pref,setting in k.items():
                    if not opts.get('echo'):
                        if pref == 'NAME':
                            opts['echo'] = setting
                    if not opts.get('shared'):
                        if pref == 'COMMON':
                            opts['shared'] = setting
                            
    if not opts.get('type'):
        opts['type'] = 'default'

    if not opts.get('config'):
        try:
            opts['config'] = '/etc/planter/tree.list'
        except:
            print('Failed: No template file found.')
            exit()

    if opts.get('gui'):
        from PyQt5.QtWidgets import QApplication
    elif not opts.get('gui'):
        opts['gui'] = 0

    else:
        import shell
        shell.execute(opts)

    if opts['gui'] == 0:
        import shell
        shell.execute(opts)
    else:
        import gui
        gui.execute(opts)
